package org.dtrd.modules.service.controller;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.aspect.annotation.AutoLog;
import org.dtrd.common.system.util.JwtUtil;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.service.entity.bean.ServicePackageInfo;
import org.dtrd.modules.service.entity.request.EditPackageRequest;
import org.dtrd.modules.service.entity.request.EditServiceRequest;
import org.dtrd.modules.service.entity.bean.ServicePackage;
import org.dtrd.modules.service.service.IDtrdEntRdServicePackageService;
import org.dtrd.modules.service.service.IDtrdRlServicePackageService;
import org.dtrd.modules.service.service.impl.DtrdRlPackagePatientServiceImpl;
import org.dtrd.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static org.dtrd.common.constant.CommonConstant.*;
import static org.dtrd.config.system.SystemState.ResponseState.*;

/**
 * <p>
 * 服务包信息 前端控制器
 * </p>
 *
 * @author QR
 * @since 2021-11-19 18:52:54
 */
@Api(tags = "服务套餐")
@RestController
@RequestMapping("/107/03")
@Slf4j
public class ServicePackageController extends BaseController {

    @Autowired
    private IDtrdEntRdServicePackageService packageService;
    @Autowired
    private IDtrdRlServicePackageService servicePackageService;
    @Autowired
    private DtrdRlPackagePatientServiceImpl packagePatientRlService;
    @Autowired
    private BaseCommonService baseCommonService;
    @Autowired
    private ISysUserService sysUserService;


    @ApiOperation(value = "获取服务包列表",notes = "机构编码为空则查询所有的服务包列表",response = ServicePackageInfo.class)
    @GetMapping("/1070309")
    @AutoLog(value="获取服务包列表", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getServicePackageList(@PathParam(value = "orgCode") String orgCode) {
//        List<ServicePackageInfo> servicePackageInfoList = packageService.getServicePackageList();
        List<ServicePackageInfo> servicePackageInfoList = packageService.getServicePackageList(orgCode);
        return Result.OK(servicePackageInfoList);
    }


    @ApiOperation(value = "新增或修改服务包内容", notes = "dataId == null 为新增, dataId != null 修改")
    @PostMapping("/1070310")
    public Result<?> saveOrUpdateServicePackage(@RequestBody @Validated ServicePackageInfo servicePackageInfo,
                                                HttpServletRequest request){
        // 判断 名字 / 周期 / 原价
        String packageName = servicePackageInfo.getPackageName();
        Integer packageId = servicePackageInfo.getDataId();
        if (packageService.hasSamePackageName(packageId, packageName, servicePackageInfo.getOrgCode())) {
            return Result.error("不能有同名的服务包");
        }
        String username = JwtUtil.getUserNameByToken(request);
        log.info("--------------------用户id: {} 正在编辑服务包内容--------------------", username);
//        // 获取到当前登陆用户的 orgCode
        String orgCode = sysUserService.getArgCodeByUsername(username);
        boolean result = packageService.saveOrUpdateServicePackage(servicePackageInfo, orgCode);
        String logContent = String.format("添加服务包, 服务包内容：%s", servicePackageInfo);
        baseCommonService.addLog(logContent, OPERATE_TYPE_ADD);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }


    @ApiOperation(value = "编辑服务包内容", notes = "保存的时候直接把整个获取的列表对象传到 services, 周期用逗号隔开形成字符串")
    @PostMapping("/1070311")
    public Result<?> editServicePackage(@RequestBody EditPackageRequest request){
        // 校验 packageId 的有效性
        Integer packageId = request.getPackageId();
        if (!packageService.isValidPackageId(packageId)){
            return error(STATE_PARAMS_ERROR);
        }
        // 服务中的服务包无法新添加服务项
        List<EditServiceRequest> services = request.getServices();
        // List<Integer> serviceIds = request.getServices().stream()
        //         .filter(EditServiceRequest::isFlag)
        //         .map(EditServiceRequest::getDataId)
        //         .collect(Collectors.toList());
        // if (!packagePatientRlService.isPackageServing(packageId, serviceIds)) {
        //     return Result.error("该服务包正在服务中无法添加新服务");
        // }
//        if (packagePatientRlService.checkPackageRelatePatient(packageId)) {
//            return Result.error("服务包已关联患者, 无法修改");
//        }
        // serviceId 一定不能没有
        Optional<EditServiceRequest> any = services.stream()
                .filter(dto -> isIntParamInvalid(dto.getDataId())
                        //  如果设置了所属标记服务周期不能为空
                        || (dto.isFlag() && StrUtil.isBlank(dto.getServiceMonth())))
                .findAny();
        if (any.isPresent()) {
            return Result.error("缺少服务服务周期");
        }
        boolean result = servicePackageService.editServicePackage(packageId, services);
        String logContent = String.format("添加服务包, 编辑服务包: %d, 编辑内容：%s", packageId, services);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation("删除服务包")
    @DeleteMapping("/1070312")
    public Result<?> removeServicePackage(@RequestParam Integer packageId){
        if (isIntParamInvalid(packageId)) {
            return error(STATE_PARAMS_MISSING);
        }
        if (packagePatientRlService.checkPackageRelatePatient(packageId)) {
            return Result.error("服务包已经有关联患者正在服务");
        }
        boolean result = packageService.removeServicePackage(packageId);
        String logContent = String.format("删除服务包, 删除服务包id: %d", packageId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }


    @ApiOperation(value = "获取服务包详情", response = ServicePackage.class)
    @GetMapping("/1070313")
    public Result<?> getServicePackageInfo(@RequestParam Integer packageId){
        ServicePackage servicePackage = packageService.getServicePackage(packageId);
        String logContent = String.format("获取服务包详情，查询服务包id：%d", packageId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(servicePackage);
    }
}
